package com.shed.demo.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.shed.base.domain.Page;
import com.shed.base.utils.Md5PasswordEncoder;
import com.shed.demo.dao.LoginLogDao;
import com.shed.demo.dao.UserDao;
import com.shed.demo.domain.LoginLog;
import com.shed.demo.domain.User;
import com.shed.demo.service.UserService;

public class UserServiceImpl implements UserService {
	private UserDao userDao;
	private LoginLogDao loginLogDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setLoginLogDao(LoginLogDao loginLogDao) {
		this.loginLogDao = loginLogDao;
	}

	public void createUser(User user) {
		user.setUserPwd(Md5PasswordEncoder.encodePassword(user.getUserPwd(), null));
		userDao.create(user);
	}

	public void deleteUser(Long userId) {
		userDao.remove(getUserByUserId(userId));
	}

	public List<User> findUser(Map<String, String> filter) {
		return userDao.find(filter);
	}

	public User getUserByUserId(Long userId) {
		return userDao.get(userId);
	}

	public Page pageUser(Map<String, String> filterMap, Map<String, String> likeMap, Map<String, String> sortMap,
			int pageNo, int pageSize) {
		return userDao.pagedQuery(filterMap, likeMap, sortMap, pageNo, pageSize);
	}

	public void updateUser(User user) {
		userDao.update(user);
	}

	public User getUserByUserName(String userName) {
		Map<String, String> filter = new HashMap<String, String>();
		filter.put("userName", userName);
		List<User> list = findUser(filter);
		return list.size() > 0 ? list.get(0) : new User();
	}

	public void updateUserPwd(Long userId, String userPwd) {
		User user = getUserByUserId(userId);
		user.setUserPwd(Md5PasswordEncoder.encodePassword(userPwd, null));
		updateUser(user);
	}

	public Map<String, Object> doLogin(String userName, String userPwd, String logIP) {
		Map<String, String> filter = new HashMap<String, String>();
		filter.put("userName", userName);
		filter.put("userPwd", userPwd);
		List<User> list = userDao.find(filter);
		Map<String, Object> result = new HashMap<String, Object>();
		if (list.size() > 0) {
			User user = list.get(0);
			switch (user.getUserState()) {
			case 1:
				result.put("flag", true);
				result.put("user", user);
				LoginLog loginLog = new LoginLog();
				loginLog.setLogIP(logIP);
				loginLog.setLogTime(new Date());
				loginLog.setUserName(user.getUserName());
				loginLog.setUserID(user.getUserID());
				loginLogDao.create(loginLog);
				break;
			default:
				result.put("flag", false);
				result.put("msg", "无效的用户！");
				break;
			}
		} else {
			result.put("flag", false);
			result.put("msg", "输入的工号或密码有误！");
		}
		return result;
	}
}
